package server;

import com.sun.media.jsdt.*;

public class JSDTServer {
	
	//private Channel channel;
	private Client client;
	private int hostPort;
	private String hostName;
	private Session session;
	private String sessionType = "socket";
	private Serveur server;
	private String name ="";
	
	public JSDTServer(Serveur server,String sessionType,String hostName,int port){
		this.server = server;
		this.sessionType = sessionType;
		this.hostName = hostName;
		this.hostPort = port;
		this.session = null;
		
	}
	public boolean connect(){
		boolean error = true;
		while(error){

	
		try {
			URLString url = URLString.createSessionURL(hostName, hostPort,
					sessionType, "server");
			
			if (RegistryFactory.registryExists(sessionType) == false) {
					RegistryFactory.startRegistry(sessionType);
			}

			System.out.println(url);

			this.session = SessionFactory.createSession(this.server.getClient(), url, true);
			this.session.createChannel(this.server.getClient(), "chatName",
					true, true, true);
			System.out.println("ServeurJSDT :: Ouverture du canal "
					+ "Channel chat" + this.server.getClient());
			error = false;
			

		} catch (JSDTException e) {
			// TODO Auto-generated catch block
			if (e.toString().equals("port in use")) {
				error = true;
				this.hostPort++;
				}else{
				error = false;
				e.printStackTrace();
				return false;
			}
			e.printStackTrace();
		}
		}
		return true;
	}
		
	public boolean createSession(){
		URLString url = URLString.createSessionURL(hostName,hostPort,sessionType,"wbSession");
		System.out.println(url);
		try {
			if(SessionFactory.sessionExists(url)){
					this.session = SessionFactory.createSession(this.server.getClient(),url,true);
					this.session.join(this.server.getClient());
					return true;	
			}
		} catch (JSDTException e) {
			// TODO Auto-generated catch block
			System.out.println("Couldn't create the Session :: "+e);
			
		}
		return false;	
	}
	
}
